<template>
  <div>
    <el-row class="mt10">
      <el-form :inline="true" :model="form">
        <el-form-item>
          <el-input
            v-model="form.name"
            placeholder="网格名称"
            style="width: 292px; height: 40px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            style="
              width: 144px;
              height: 40px;
              background: #0a85cb;
              border: 1px solid rgba(11, 178, 248, 1);
            "
            >查询</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button
            type="success"
            @click="addGrid"
            style="
              width: 144px;
              height: 40px;
              background: #19a65b;
              border: 1px solid rgba(31, 231, 124, 1);
            "
            >添加网格</el-button
          >
        </el-form-item>
      </el-form>
    </el-row>

    <el-row class="bbg3">
      <el-table
        :data="subGrideList.results"
        :header-cell-style="{
          'background-color': '#169098',
          color: '#fff',
        }"
        border
        height="620"
        :row-style="{
          height: '57px',
        }"
        style="width: 100%"
      >
        <el-table-column prop="name" align="center" label="网格名称">
        </el-table-column>
        <el-table-column prop="company_name" align="center" label="所属网格">
        </el-table-column>
        <el-table-column prop="type" align="center" label="级别">
        </el-table-column>
        <el-table-column prop="city_space" align="center" label="辖区面积">
        </el-table-column>
        <el-table-column prop="person_num" align="center" label="辖区人口">
        </el-table-column>
        <el-table-column prop="sort" align="center" label="排序">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-if="scope.row.id" slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="editGrid(scope.row)"
            >
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="deleteGrid(scope.row)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row class="text-center mt20">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="subGrideList.totalRecord"
      >
      </el-pagination>
    </el-row>

    <el-dialog
      title="网格信息"
      :visible.sync="grideDialogVisible"
      width="530px"
    >
      <el-form
        ref="currentGrid"
        :rules="rules"
        :model="currentGrid"
        label-width="100px"
      >
        <el-form-item label="网格名称：" prop="name">
          <el-input
            v-model="currentGrid.name"
            placeholder="请输入网格名称"
            style="width: 380px"
          ></el-input>
        </el-form-item>

        <el-form-item label="辖区面积：" prop="city_space">
          <el-input
            v-model="currentGrid.city_space"
            placeholder="请输入辖区面积"
            style="width: 380px"
          ></el-input>
        </el-form-item>

        <el-form-item label="辖区人口：" prop="person_num">
          <el-input
            v-model="currentGrid.person_num"
            placeholder="请输入辖区人口"
            style="width: 380px"
          ></el-input>
        </el-form-item>

        <el-form-item label="排序：" prop="sort">
          <el-input
            v-model="currentGrid.sort"
            placeholder="请输入网格排序"
            style="width: 380px"
          ></el-input>
        </el-form-item>
        <!-- 区级别不让画网格 -->
        <el-form-item v-if="currentGrid.type > 2">
          <el-button type="primary" @click="openmap" style="width: 380px">
            画网格
          </el-button>
        </el-form-item>
				<!--
        <el-form-item v-else label="地区：">
          <el-cascader
            style="width: 380px"
            :options="districtData"
            :props="props"
            filterable
            change-on-select
            v-model="selectedOptions"
          >
          </el-cascader>
        </el-form-item>
				-->

        <el-form-item>
          <el-row style="width: 380px">
            <el-col :span="12">
              <el-button
                type="primary"
                @click="save"
                style="
                  width: 100px;
                  background: #19a65b;
                  border: 1px solid rgba(31, 231, 124, 1);
                "
              >
                保 存
              </el-button>
            </el-col>
            <el-col :span="12" class="text-right">
              <el-button
                @click="grideDialogVisible = false"
                style="
                  width: 100px;
                  background: #0a85cb;
                  border: 1px solid rgba(11, 178, 248, 1);
                  color: #fff;
                "
                >取 消</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <el-dialog
        width="70%"
        fullscreen
        :visible.sync="mapVisible"
        append-to-body
      >
        <div slot="title">
          <el-row>
            <el-col :span="8">
              <el-amap-search-box
                class="search-box"
                size="mini"
                :default="'沈阳市'"
                :search-option="searchOption"
                :on-search-result="onSearchResult"
              ></el-amap-search-box>
            </el-col>
            <el-col :span="14" class="text-right">
              <el-button type="primary" @click="saveGrid" class="mt5"
                >保 存</el-button
              >
            </el-col>
          </el-row>
        </div>

        <div
          :style="{ width: offsetwidth + 'px', height: offsetheight + 'px' }"
        >
          <el-amap
            vid="amapDemo"
            :center="center"
            :amap-manager="amapManager"
            :zoom="zoom"
            class="amap-demo"
          >
            <el-amap-polygon
              :path="polygon.path"
              :editable="polygon.editable"
            ></el-amap-polygon>
            <el-amap-polygon
              v-for="(item, index) in polygon.otherpath"
              :key="index"
              :path="item"
              :editable="false"
            ></el-amap-polygon>

            <el-amap-polygon
              :fillOpacity="0"
              :path="polygon.parentPath"
              :editable="false"
            ></el-amap-polygon>
          </el-amap>
        </div>
        <!-- <span slot="footer" class="dialog-footer">
			<el-button @click="mapVisible = false">取 消</el-button>
			<el-button type="primary" @click="saveGrid">保 存</el-button>
		</span> -->
      </el-dialog>

      <!-- <span slot="footer" class="dialog-footer">
    <el-button @click="grideDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">保 存</el-button>
  </span> -->
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import District from "ydui-district/dist/gov_province_city_area_id";
import VueAMap from "vue-amap";
import Vue from "vue";

let amapManager = new VueAMap.AMapManager();

export default {
  name: "gride",

  data() {
    return {
      pageNo: 1,
      pageSize: 10,

      gridid: this.obj.id,

      parentGrid: this.obj,

      form: {},
      subGrideList: {},

      currentGrid: { city_space: "0", person_num: "0" },
      what: "",
      grideDialogVisible: false,

      selectedOptions: [],

      districtData: District,

      props: {
        value: "v",
        label: "n",
        children: "c",
      },

      mapVisible: false,

      zoom: 15,
      center: [],
      //center: [121.5273285, 31.21515044],
      amapManager,

      offsetwidth: document.documentElement.clientWidth - 40,
      offsetheight: document.documentElement.clientHeight - 120,

      searchOption: {
        city: "",
        citylimit: true,
      },

      polygon: {
        // path: [[121.5273285, 31.21515044], [121.5293285, 31.21515044], [121.5293285, 31.21915044], [121.5273285, 31.21515044]],

        path: [],

        otherpath: [],

        parentPath: [],

        editable: true,
      },

      rules: {
        name: [
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入网格名称", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入", trigger: "blur" }],
      },

      defaultGrid: {
        name: "",
      },
    };
  },

  props: {
    obj: {
      type: Object,
      default() {
        return {};
      },
    },
  },

  components: {},

  computed: {
    ...mapGetters({
      c: "center",
      city: "city",
    }),
  },

  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },

    handleCurrentChange(val) {
      this.pageNo = val;
      this.init();
    },

    search() {
      this.pageNo = 1;
      this.init();
    },

    init() {
      this.$http({
        fun: "subGrideList",
        id: this.gridid,
        name: this.form.name,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        cb: (res) => {
          console.log("subGrideList");
          console.log(res);
          //this.subGrideList = res;
          this.subGrideList = this.$util.tableAdd(res);
        },
      });
    },

    addGrid(item) {
      this.selectedOptions = [];
      this.currentGrid = {
        parent_id: this.gridid,
        parent_ids: this.parentGrid.parent_ids + this.gridid + ",",
        //citys : [],
        type: parseInt(this.parentGrid.type) + 1,
        sort: 0,
        map: {
          path: [],
          center: this.c,
        },
      };
      this.what = "add";
      this.grideDialogVisible = true;
    },

    editGrid(item) {
      console.log(item);
      this.currentGrid = {
        ...item,
        //citys : item.city_name ? item.city_name.split(',') : [],
        map: item.mapinfo
          ? eval('('+item.mapinfo+')')
          : {
              path: [],
              center: this.c,
            },
      };
      this.selectedOptions = item.city_name ? item.city_name.split(",") : [];
      this.what = "edit";
      this.grideDialogVisible = true;
    },

    addCity() {
      this.currentGrid.citys.push(this.selectedOptions.join(""));
    },

    handleClose(index) {
      this.currentGrid.citys.splice(index, 1);
    },

    save() {
      this.$refs["currentGrid"].validate((valid) => {
        if (valid) {
          let para = {
            fun: "createGrides",
            name: this.currentGrid.name,
            city_space: this.currentGrid.city_space,
            person_num: this.currentGrid.person_num,
            sort: this.currentGrid.sort,
            cb: (res) => {
              console.log(res);
              this.$message.success("操作成功");
              this.grideDialogVisible = false;
              this.init();
            },
          };

          if (this.what == "add") {
            para["parent_id"] = this.currentGrid.parent_id;
            para["parent_ids"] = this.currentGrid.parent_ids;
            para["type"] = this.currentGrid.type;
          } else if (this.what == "edit") {
            para["parent_id"] = this.currentGrid.parent_id;
            para["id"] = this.currentGrid.id;
          }

          console.log(this.currentGrid.type);

          if (parseInt(this.currentGrid.type) > 1 && parseInt(this.currentGrid.type) <= 4) {
            //镇，村
            para["mapinfo"] = this.currentGrid.mapinfo;
          } else {
            //市，区/县
            para["city_name"] = this.selectedOptions.join(",");
            para["mapinfo"] = this.selectedOptions[
              this.selectedOptions.length - 1
            ];
          }

          if(!para["mapinfo"]) {
            para["mapinfo"] = '210102'
          }
          console.log("==========================================:", para["mapinfo"]);

          this.$http(para);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    deleteGrid(item) {
      this.$confirm("此操作将永久删除该网格, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            fun: "createGride",
            id: item.id,
            del_flag: 1,
            cb: (res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            },
            err: (res) => {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            },
          });
        })
        .catch(() => {});
    },

    openmap() {
      this.polygon.path = [];
      this.polygon.otherpath = [];
      this.polygon.parentPath = [];

      const parentType = this.parentGrid.type;

      this.$http({
        fun: "allChildrenList",
        grid_id: this.gridid,
        cb: (res) => {
          res.forEach((item) => {
            if (item.mapinfo != undefined) {
              if (item.id == this.gridid) {
                //父级
                console.log(item.mapinfo);

                let c = [];

                if (item.type == "2") {
                  AMap.plugin("AMap.DistrictSearch", () => {
                    // 创建行政区查询对象
                    var district = new AMap.DistrictSearch({
                      // 返回行政区边界坐标等具体信息
                      extensions: "all",
                      // 设置查询行政区级别为 区
                      level: "district",
                    });

                    district.search(item.mapinfo.split(','), (status, result) => {
                      console.log('什么玩意???', result);
                      this.polygon.parentPath =
                        result.districtList[0].boundaries;
                      //新增状态，以上级中心点作为中心。编辑状态，如果没画网格的话，也默认成上级中心点。
                      if (
                        this.currentGrid.id == undefined ||
                        (this.currentGrid.id != undefined &&
                          this.currentGrid.map.path.length == 0)
                      ) {
                        this.center = [
                          result.districtList[0].center.lng,
                          result.districtList[0].center.lat,
                        ];

                        this.polygon.path = [
                          [this.center[0] - 0.002, this.center[1] - 0.002],
                          [this.center[0] + 0.002, this.center[1] - 0.002],
                          [this.center[0] + 0.002, this.center[1] + 0.002],
                          [this.center[0] - 0.002, this.center[1] + 0.002],
                        ];
                      }
                    });
                  });
                } 
                else if (item.type > 2) {
									console.log('=======================', eval('('+item.mapinfo+')'))
                  const obj = eval('('+item.mapinfo+')');
                  this.polygon.parentPath = obj.path;
                  //新增状态，以上级中心点作为中心。编辑状态，如果没画网格的话，也默认成上级中心点。
                  if (
                    this.currentGrid.id == undefined ||
                    (this.currentGrid.id != undefined &&
                      this.currentGrid.map.path.length == 0)
                  ) {
                    this.center = obj.center;
                    this.polygon.path = [
                      [this.center[0] - 0.002, this.center[1] - 0.002],
                      [this.center[0] + 0.002, this.center[1] - 0.002],
                      [this.center[0] + 0.002, this.center[1] + 0.002],
                      [this.center[0] - 0.002, this.center[1] + 0.002],
                    ];
                  }
                }
                console.log("中心点");
                console.log(this.center);
                console.log(this.polygon.path);
              } else if (
                item.type != parentType &&
                item.id != this.currentGrid.id
              ) {
                //其他子级
                const obj = eval('('+item.mapinfo+')');
                this.polygon.otherpath.push(obj.path);
              }
            }
          });
          if (this.currentGrid.id != undefined) {
            this.center = this.currentGrid.map.center;
            this.polygon.path = this.currentGrid.map.path;
          }
          this.mapVisible = true;
        },
      });
    },

    saveGrid() {
      console.log(this.polygon.path);
      console.log(this.center);
      let arr = [];
      let latSum = 0;
      let lngSum = 0;

      this.polygon.path.forEach((item) => {
        arr.push([item.lng, item.lat]);
        lngSum += item.lng;
        latSum += item.lat;
      });

      let center = [
        lngSum / this.polygon.path.length,
        latSum / this.polygon.path.length,
      ];

      this.currentGrid.mapinfo = JSON.stringify({
        center,
        path: arr,
      });

      this.mapVisible = false;
    },

    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      console.log(pois);
      if (pois.length > 0) {
        pois.forEach((poi) => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          //this.markers.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length,
        };

        this.center = [center.lng, center.lat];
        this.polygon.path = [
          [center.lng - 0.002, center.lat - 0.002],
          [center.lng + 0.002, center.lat - 0.002],
          [center.lng + 0.002, center.lat + 0.002],
          [center.lng - 0.002, center.lat + 0.002],
        ];
      }
    },

    start() {
      this.polygon.editable = !this.polygon.editable;
    },
  },

  watch: {},

  mounted() {
    this.init();

    console.log(this.districtData);

    this.center = this.c;
    this.searchOption.city = this.city;
  },
};
</script>

<style scoped>
</style>
